﻿function LoadItem(rows) {
    $("#hTradeOrderID").val(rows.TradeOrderID);
    $('#hFromWarehouseID').val(rows.FromWarehouseID);
    $('#tTradeOrderNO').textbox('setValue', rows.TradeOrderNO);
    $('#tCreateTime').textbox('setValue', rows.TradeDate);
    $('#tSourceOrderNO').textbox('setValue', rows.SourceOrderNO);
}
$(function () {
    // 使用window.location.href获取当前URL
    const url = new URL(window.location.href);
    // 使用URLSearchParams接口获取URL参数
    const params = new URLSearchParams(url.search);
    const pa = JSON.parse(decodeURIComponent(params.get('params')));
    // 初始化
    if (pa != null) {
        LoadItem(pa);
        const view = params.get('view');
        if (view == "view") {
            /* $("#A1").style.display= "none";*/
            $('#A3').hide();
            $('#A2').hide();
        }
    } else {
        $('#tb').find('input.easyui-textbox').textbox('setValue', '');
    }
    $('#s').on('dblclick', function () {
        $('#MaterialDialog').find('input.easyui-textbox').textbox('setValue', '');
        $('#MaterialDialog').dialog('open');
        MaterialLocal();
    });
    //收料明细
    $('#ItemDate').datagrid({
        pageSize: 20,
        loadMsg: "LoadIng...",
        method: 'Get',
        iconCls: 'icon-reload',
        url: '/api/WMS/QueryWmsTradeSource',
        queryParams: {
            TradeOrderID: $("#hTradeOrderID").val(),
            MaterialNO: "",
            sort: "",
            order: ""
        },
        height: window.innerHeight - 150,
        idField: 'TradeSourceID',
        striped: true,      //隔行变色
        singleSelect: true, //是否单选
        pagination: true,   //分页控件
        scrollbarSize: 0,
        fitColumns: false,
        columns: [[
            {
                field: 'TradeSourceID', // 复选框字段
                checkbox: true // 表示这是一个复选框列
            },
            { field: 'ErpItem', title: 'ErpItem', width: 90, sortable: true },
            { field: 'MaterialNO', title: 'MaterialNO', width: 150, sortable: true },
            { field: 'BatchNO', title: 'BatchNO', width: 100 },
            { field: 'StorageNO', title: 'StorageNO', width: 100, sortable: true},
            { field: 'WarehouseNO', title: 'WarehouseNO', width: 100 },
            { field: 'RequestQty', title: 'RequestQty', width: 100},
            { field: 'CalculateQty', title: 'CalculateQty', width: 120, sortable: true },
            { field: 'ActionQty', title: 'ActionQty', width: 80, sortable: true  },
            { field: 'LackQty', title: 'LackQty', width: 80 },
            { field: 'MaterialName', title: 'MaterialName' },
            { field: 'MaterialDesc', title: 'MaterialDesc' },
            { field: 'LackColor', hidden: true }

        ]],
        rowStyler: function (index, row) {
            return row.LackColor;
        },
        loadFilter: function (data) {
            return JSON.parse(data);
        },
        toolbar: "#toolbar",
        rownumbers: true,   //行号
        onLoadSuccess: function (data) {
            $('#ItemDate').datagrid("fillRows");
            $('#ItemDate').datagrid('resize');
        },
        onDblClickRow: function (index, row) {
            if (row == null) {
                Alert("Please Select One Row");
                return false;
            }
            $('#hTradeSourceID').val(row.TradeSourceID);
            $('#SWarehouseNO').textbox('setValue', row.WarehouseNO);
            $('#SMaterialNO').textbox('setValue', row.MaterialNO);
            $('#StockMaterial').dialog('open');
            StockMaterialQuery();
        
        },
        onSortColumn: function (sort, order) {
            $("#hSort").val(order);
            $("#hOrder").val(sort);
        }
    });

    //条码明细
    $('#CodeItem').datagrid({
        pageSize: 20,
        loadMsg: "LoadIng...",
        method: 'Get',
        iconCls: 'icon-reload',
        url: '/api/WMS/QueryWmsTradebarcode',
        queryParams: {
            TradeOrderID: $("#hTradeOrderID").val(),
            MaterialNO: "",
            sort: "",
            order: ""
        },
        height: window.innerHeight - 150,
        idField: 'TradebarcodeID',
        striped: true,      //隔行变色
        singleSelect: true, //是否单选
        pagination: true,   //分页控件
        scrollbarSize: 0,
        fitColumns: false,
        columns: [[
            {
                field: 'TradebarcodeID', // 复选框字段
                checkbox: true // 表示这是一个复选框列
            },
            { field: 'BarcodeNO', title: 'BarcodeNO', width: 150, sortable: true },
            { field: 'RStateName', title: 'State', width: 100 },
            { field: 'LampNO', title: 'LampNO', width: 100, sortable: true},
            { field: 'MaterialNO', title: 'MaterialNO', width: 150, sortable: true },
            { field: 'BatchNO', title: 'BatchNO', width: 100 },
            { field: 'Qty', title: 'Qty', width: 70},
            { field: 'WarehouseName', title: 'WarehouseName', width: 150},
            { field: 'StorageNO', title: 'StorageNO', width: 150 },
            { field: 'MaterialName', title: 'MaterialName' },
            { field: 'MaterialDesc', title: 'MaterialDesc' }

        ]],
        loadFilter: function (data) {
            return JSON.parse(data);
        },
        toolbar: "#CodeBar",
        rownumbers: true,   //行号
        onLoadSuccess: function (data) {
            $('#CodeItem').datagrid("fillRows");
            $('#CodeItem').datagrid('resize');
        },
        onSortColumn: function (sort, order) {
            $("#hSort").val(order);
            $("#hOrder").val(sort);
        }
    });
    // 下拉框加载 - 调出仓库
    $('#tFromWarehouseID').combobox({
        url: '/api/BAS/GetWarehouseInfo',
        method: 'POST',
        valueField: 'WarehouseID',
        textField: 'WarehouseName',
        panelHeight: 'auto',
        editable: false,
        label: 'WareName:',
        required: true,
        onLoadSuccess: function (data) {
            // 获取隐藏字段的值
            var hiddenValue = $('#hFromWarehouseID').val();
            if (hiddenValue) {
                // 如果隐藏字段有值，尝试匹配并选中
                var matched = false;
                $.each(data, function (index, item) {
                    if (item.WarehouseID == hiddenValue) {
                        $('#tFromWarehouseID').combobox('setValue', item.WarehouseID);
                        matched = true;
                        return false; // 退出循环
                    }
                });
            } else {
                // 如果隐藏字段没有值，默认选中第一个
                if (data && data.length > 0) {
                    $('#tFromWarehouseID').combobox('setValue', data[0].WarehouseID);
                    $('#hFromWarehouseID').val(data[0].WarehouseID); // 同步到隐藏字段
                }
            }
        },
        onLoadError: function (error) {
            console.error('调出仓库加载失败:', error);
        },
        onChange: function (newVal) {
            $('#hFromWarehouseID').val(newVal); // 更新隐藏字段
        }
    });

    $('#tts').datagrid({
        loadMsg: "正在接收数据...",
        iconCls: 'icon-reload',
        url: '',
        idField: 'MaterialID',
        autoRowHeight: false,
        fitColumns: false,
        scrollbarSize: 0,
        height: document.documentElement.clientHeight - 250,
        pageSize: 20,
        sortable: true,
        striped: true,      //隔行变色
        singleSelect: true, //是否单选
        pagination: true,   //分页控件
        rownumbers: true,
        columns: [[
            { field: 'IsSelect', checkbox: true },
            { field: 'MaterialID', hidden: true },
            //{ field: 'MaterialType', hidden: true },
            { field: 'MaterialNO', width: 150, title: '物料编号', sortable: true },
            { field: 'MaterialName', width: 250, title: '物料名称' },
            { field: 'MaterialDesc', width: 350, title: '物料规格' }

        ]],
        onDblClickRow: function (index, row) {
            if (row == null) {
                Alert("请选择一行数据");
                return false;
            }
            $('#hMaterialID').val(row.MaterialID);
            $("#tMaterialNO").textbox('setValue', row.MaterialNO);
            $("#tMaterialName").textbox('setValue', row.MaterialName);
            $("#tMaterialDesc").textbox('setValue', row.MaterialDesc);
            $('#MaterialDialog').dialog('close');
        },
        loadFilter: function (data) {
            if (data.d) {
                return data.d;
            } else {
                return JSON.parse(data);
            }
        }
    });
    $('#tms').datagrid({
        loadMsg: "正在接收数据...",
        iconCls: 'icon-reload',
        idField: 'StockMaterialID',

        autoRowHeight: false,
        fitColumns: false,
        scrollbarSize: 0,
        height: document.documentElement.clientHeight - 250,
        pageSize: 20,
        sortable: true,
        striped: true,      //隔行变色
        singleSelect: true, //是否单选
        pagination: false,   //分页控件
        rownumbers: true,
        columns: [[
            { field: 'StockMaterialID', checkbox: true },
            { field: 'MaterialID', hidden: true },
            { field: 'StorageID', hidden: true },
            { field: 'WarehouseID', hidden: true },
            //{ field: 'MaterialType', hidden: true },
            { field: 'MaterialNO', width: 150, title: '物料编号', sortable: true },
            { field: 'BatchNO', width: 150, title: '批号', sortable: true },
            { field: 'StorageNO', width: 150, title: '储位', sortable: true },
            { field: 'StockQty', width: 150, title: '数量' },
            { field: 'MaterialName', width: 250, title: '物料名称' },
            { field: 'MaterialDesc', width: 350, title: '物料规格' }

        ]],
        onDblClickRow: function (index, row) {
            if (row == null) {
                Alert("请选择一行数据");
                return false;
            }
            var TradeSourceID = $('#hTradeSourceID').val();
            var StorageID = row.StorageID;
            var WarehouseID = row.WarehouseID;
            var BatchNO = row.BatchNO;
            var MaterialID = row.MaterialID;
            var url = '/api/WMS/ChanegTradeSouece';
            var MateialInfo =
            {
                TradeSourceID: TradeSourceID,
                StorageID: StorageID,
                WarehouseID: WarehouseID,
                BatchNO: BatchNO,
                MaterialID: MaterialID
            }
            DataService.PostJson(url, MateialInfo, function (error, response) {
                if (error) {
                    Notice("success!");
                    $('#StockMaterial').dialog('close');
                    SInItem();
                } else {
                    Alert(response.Message);
                }
            })
      
        },
        loadFilter: function (data) {
            if (data.d) {
                return data.d;
            } else {
                return JSON.parse(data);
            }
        }
    });

    $(window).resize(function () {
        $('#ItemDate').datagrid('resize');
    });
})

function Delete() {
    var rows = $('#ItemDate').datagrid('getSelections');
    if (rows.length < 1) {
        Alert("Please select！");
        return false;
    }
    Confirm("Confirm to delete" + rows.length + "Is it a receipt？", function () {
        var MateialInfo = fnSelectList('ItemDate', rows);
        var url = '/api/WMS/DeleteWmsTradeSource';
        DataService.PostJson(url, MateialInfo, function (error, response) {
            if (error) {
                Notice("success!");
                SInItem();
            } else {
                Alert(response);
            }
        })
    });
}

//批号默认生成
function BatchData() {
    // 获取当前文本框的值
    var currentValue = $('#tBatchNO').textbox('getValue');

    // 如果当前没有值或者值为空字符串，则设置默认值
    if (!currentValue || currentValue.trim() === '') {
        var today = new Date();
        var yyyy = today.getFullYear();
        var mm = String(today.getMonth() + 1).padStart(2, '0');
        var dd = String(today.getDate()).padStart(2, '0');
        var formattedDate = yyyy + mm + dd;
        $('#tBatchNO').textbox('setValue', formattedDate);
    }
    // 如果已经有值，则不做任何修改
}

//新增明细保存
function ItemBarCodeSave() {
    if (!validateForm()) {
        return;
    }
    var Qty = $('#tQty').textbox('getValue');

    var SouceItem = {
        TradeOrderID: $("#hTradeOrderID").val(),
        MaterialID: $('#hMaterialID').val(),
        RequestQty: parseFloat(Qty),
        BatchNO: $("#tBatchNO").textbox('getValue'),
        StorageNO: $('#tStorage').textbox('getValue'),
        FromWarehouseID: $('#hFromWarehouseID').val()
    };
    var url = '/api/WMS/SaveSouceItem';
    DataService.PostJson(url, SouceItem, function (err, res) {
        if (err) {
            Notice("Success!");
            console.log(res);
            SInItem();
        } else {
            Alert("Error." + res);
        }
    });
    ItemClear();
}

//新增取消
function ItemClear() {
    $('#dd').drawer({
        onCollapse: function () {
            // 抽屉关闭后的逻辑处理
            console.log('抽屉已关闭');
            // 添加您想要执行的操作
        }
    });
}
//添加来源数据
function addBlankRow() {
    $('#hMaterialID').val("");
    $('#dd').find('input.easyui-textbox').textbox('setValue', '');
    BatchData();
    $('#dd').drawer('expand');
}
function MaterialLocal() {
    var MaterialNO = $("#DMaterialNO").val();
    var MaterialName = $("#DMaterialName").val();
    $("#tts").datagrid({
        url: '/api/BAS/QueryMaterial',
        method: 'Get',
        queryParams: {
            MaterialNO: MaterialNO,
            MaterialName: MaterialName,
            order: '',
            sort: ''
        },
        loadFilter: function (data) {
            if (data.d) {
                return data.d;
            } else {
                return JSON.parse(data);
            }
        }
    });
}


function StockMaterialQuery() {
    var WarehouseNO = $("#SWarehouseNO").val();
    var MaterialNO = $("#SMaterialNO").val();
    $('#tms').datagrid({
        url: '/api/WMS/StockMaterialQuery',
        method: 'Get',
        queryParams: {
            MaterialNO: MaterialNO,
            WarehouseNO: WarehouseNO,
            order: '',
            sort: ''
        },
        loadFilter: function (data) {
            if (data.d) {
                return data.d;
            } else {
                return JSON.parse(data);
            }
        }
    });
}

function myformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}
function myparser(s) {
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0], 10);
    var m = parseInt(ss[1], 10);
    var d = parseInt(ss[2], 10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        return new Date(y, m - 1, d);
    } else {
        return new Date();
    }
}
//新增保存
function ItemSave() {
    //if (!validateForm()) {
    //    return;
    //}
    var url = "/api/WMS/SaveTradeInfo";
    var TradeOrderNO = $("#tTradeOrderNO").val();
    var datalist = {
        TradeOrderID: $("#hTradeOrderID").val(),
        TradeOrderNO: TradeOrderNO,
        CreateTime: $("#tCreateTime").val(),
        FromWarehouseID: $("#hFromWarehouseID").val(),
        SourceOrderNO: $("#tSourceOrderNO").val(),
        TradeType: 3
    }
    DataService.PostJson(url, datalist, (err, res) => {
        if (err) {
            Notice("success");
            console.log(res);
            $("#hTradeOrderID").val(res.Items[0].TradeOrderID);
            if (!TradeOrderNO || TradeOrderNO.trim() === "") {
                $("#tTradeOrderNO").textbox("setValue", res.Items[0].TradeOrderNO);
            }
            SInItem();
        } else {
            Alert(res);
        }
    })
}

//收料明细检索
function SInItem() {
    var TradeOrderID = $("#hTradeOrderID").val();
    var MaterialNO = $('#txtProduct').val();
    var sort = $("#hSort").val();
    var order = $("#hOrder").val();
    //排序字段
    $("#ItemDate").datagrid({
        method: 'Get',
        url: '/api/WMS/QueryWmsTradeSource',
        queryParams: {
            TradeOrderID: TradeOrderID,
            MaterialNO: MaterialNO,
            sort: sort,
            order: order
        },
        loadFilter: function (data) {
            return JSON.parse(data);
        }
    });
    $('#ItemDate').datagrid('unselectAll', 'true');
    $('#tts').datagrid('unselectAll', 'true');
}
//条码明细检索
function CodeItem() {
    var TradeOrderID = $("#hTradeOrderID").val();
    var MaterialNO = $('#txtCodeNO').val();
    var sort = $("#hSort").val();
    var order = $("#hOrder").val();
    //排序字段
    $("#CodeItem").datagrid({
        method: 'Get',
        url: '/api/WMS/QueryWmsTradebarcode',
        queryParams: {
            TradeOrderID: TradeOrderID,
            MaterialNO: MaterialNO,
            sort: sort,
            order: order
        },
        loadFilter: function (data) {
            return JSON.parse(data);
        }
    });
    $('#CodeItem').datagrid('unselectAll', 'true');
}
//导入
function ExeclTo() {
    OpenSubWindow("来源明细信息导入", "WMS/UI/WMS_Order_ShelveItem.aspx?params=" + $("#hTradeOrderID").val(), 500, 280, function () {
        SInItem();
    });
}